package com.ligq.common.utils

import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment

class PermissionFragment : Fragment() {
    private var result: ((grantResults: IntArray) -> Unit)? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        retainInstance = true
    }

    fun checkPermission(result: ((grantResults: IntArray) -> Unit)?) {
        this.result = result
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(PermissionUtils.permissions, 1)
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        if (requestCode == 1) {
            PermissionUtils.clearPermissions()
            for (i in grantResults.indices) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    Log.d(
                        TAG,
                        "onRequestPermissionsResult: " + permissions[i] + " get permission failed!!"
                    )
                } else {
                    PermissionUtils.addPermission(permissions[i])
                }
            }
        }
        result?.let { it(grantResults) }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }
}